define(function (require, exports, module) {
    require("apps/lab/page.css");
    require("apps/easyui");
    require("apps/grid");

    var comp = require("apps/lab/components");
    var filedComponent = comp.components;

    exports.init = function (ctx, uuid, config) {
        var page = new $.PageDomFactory(uuid);
        var globalWindow = new $.PageWindow();

        var pageListComponent = new $.PageListComponent(uuid, {
            view: {
                grid: "grid",
                myToolbar: "news_tb",
                colbar: "user_list_btn"
            },
            configs: {
                gridUrl: ctx + "/app/api/ebom/list?status=PUBLISH",
                idField: "id",
                treeField: "eName",
                gridColumns: [
                    {
                        field: 'id',
                        checkbox: false,
                        hidden:true
                    },
                    {
                        field: 'temp1',
                        hidden: true
                    },
                    {
                        field: 'eName',
                        title: '名称',
                        width: 150,
                        align: 'left'
                    },
                    {
                        field: 'code',
                        title: '编码',
                        width: 100,
                        align: 'left'
                    },
                    {
                        field: 'pBomDes',
                        title: '设计结构',
                        width: 100,
                        align: 'left'
                    },
                    {
                        field: 'bomType',
                        title: '是否装配',
                        width: 100,
                        hidden: true,
                        align: 'left',
                        formatter: function (value, row, index) {
                            return value == "E_BOM_TYPE_UN_BUILD" ? "未装配" : "已装配";
                        }
                    },
                    {
                        field: 'description',
                        title: '功能',
                        width: 100,
                        align: 'left',
                        hidden: true
                    },
                    {
                        field: 'remark',
                        title: '备注',
                        hidden: true,
                        width: 50,
                        align: 'left'
                    },
                    {
                        field: 'cover',
                        title: '封面',
                        width: 100,
                        hidden: true,
                        align: 'left',
                        formatter: function (value, row, index) {
                            return "<img src=\"" + ctx + "/print/" + value + "\" style=\"width:48px;height:32px;\"/>"
                        }
                    },
                    {
                        field: 'createTime',
                        title: '装配时间',
                        width: 100,
                        hidden: true,
                        align: 'left'
                    }
                ]
            },
            events: {
                renderColBarBefore: function (key, row) {
                    return true;
                },
                onClickColBtn: function (context, btn, row) {
                    switch (btn.key) {
                        case "history":
                            whenViewHistory(row.id);
                            break;
                        case "view":
                            whenView(context, row);
                            break;
                        default :
                            break;
                    }
                },
                onClickToolbarBtn: function (context, btn) {
                    switch (btn.key) {
                        case "search_all":
                            context.searchAll();
                            break;
                        case "search":
                            context.search(btn.href, "装配结构搜索", "ebom_search");
                            break;
                        default :
                            break;
                    }
                }
            }
        });

        function whenView(context, row) {
            globalWindow.create({
                href: ctx + "/app/api/ebom/view?id=" + row.id,
                width: 800,
                title: row.eName + "的结构查看"
            });
            globalWindow.open();
        }

        var cache = {};
        if(config.ebomId){
            whenViewHistory(config.ebomId);
        }

        var processTools = null;
        function getProcessTool(){
            if(!processTools){
                $.ajax({
                    async:false,
                    url:ctx + "/app/api/directory/list",
                    data:{dirGroup: "DIRECTORY_PROCESS_TOOL"},
                    type:"GET",
                    dataType:"JSON",
                    success:function(data){
                        var content = data.content;
                        var options = content.map(function (item) {
                            return "<option value=\"" + item.dirValue + "\">" + item.dirValue + "</option>";
                        });
                        processTools  = options.join("");
                    }
                });
            }return processTools;
        }

        var templateForDialog = '<div class="input-250"><div class="box_tc_s"><input type="hidden" data-id="id" name="id" value="{{id}}" />' +
            '<table border="1" cellpadding="0" cellspacing="0" class="hydra-table">' +
            '{{#attrParams}}<tr class="hydra-tr-bg"><td class="hydra-left">{{fieldName}}</td>' +
            '<td class="hydra-right"><input type="hidden" value="{{fieldName}}" name="fieldName" />' +
            '<input type="hidden" value="{{unit}}" name="unit" /><input type="hidden" value="{{fieldType}}" name="fieldType" />' +
            '<input type="hidden" value="{{orderNo}}" name="orderNo" />' +
            '<span data-id="component">组件加载中</span>{{unit}}{{#useDevice}}' +
            '<span data-device-value="{{parameterDevice}}" class="ml10">测量工具：</span>' +
            '<select data-id="device" name="parameterDevice" class="hydra-input-width" style="width: 100px;"></select>{{/useDevice}}' +
            '</td></tr>{{/attrParams}}</table></div></div>';

        function modifyProcess(id) {
            $.getJSON(ctx + "/app/api/lab/record", {id:id}, function(data){
                var processName = data.tProcessTemplate.processName, values = data.tProcessParameters, attrParams = data.tProcessTemplate.tProcessAttributes;
                var uuid = $.utils.createUUID(12);
                for(var i= 0, l = attrParams.length; i < l; i++){
                    for(var j= 0, ll = values.length; j < ll; j++){
                        if (attrParams[i].fieldName == values[j].fieldName) {
                            attrParams[i].parameterValue = values[j].parameterValue;
                            attrParams[i].unit = (values[j].unit == "无" || !values[j].unit) ? "" : values[j].unit;
                            attrParams[i].parameterDevice = values[j].parameterDevice;
                            break;
                        }
                    }
                }
                var panel = $(Mustache.render(templateForDialog, {id:id, attrParams:attrParams})).appendTo("body").attr("id", uuid);
                panel.find("[data-id=device]").each(function(){
                    $(this).html(getProcessTool()).combobox({editable: false});
                    var v = $(this).prev().attr("data-device-value");
                    $(this).combobox("select", v);
                });
                panel.find("[data-id=component]").each(function (i) {
                    filedComponent[attrParams[i].fieldType].call(this, ctx, $.extend({name: "parameterValue"}, attrParams[i]), attrParams[i].parameterValue);
                });
                panel.dialog({
                    width: 600,
                    height: 500,
                    modal: true,
                    closable: true,
                    loadingMessage: '页面加载中，请稍后...',
                    title: "修改" + processName + "参数",
                    onClose: function () {
                        panel.dialog("destroy");
                        panel.remove()
                    },
                    buttons: [
                        {
                            text: "确认",
                            handler: function () {
                                var tProcessParameters = [];
                                panel.find("tr.hydra-tr-bg").each(function () {
                                    var params = $(this).serializeJson();
                                    if(params.fieldType == 'FIELD_TYPE_TABLE'){
                                        params.parameterValue = $(this).find("[data-id=f-component]").prop("outerHTML");
                                    }
                                    tProcessParameters.push(params);
                                });
                                $.post(ctx + "/app/api/lab/modifyRecord", $.utils.buildJson({id:panel.find("[data-id=id]").val(),
                                    tProcessParameters:tProcessParameters}), function(json){
                                    if ($.isErrorRequest(json)) {
                                        $.messager.alert('信息', json.msg, 'info');
                                    } else {
                                        $.messager.alert('信息', '修改成功', 'info');
                                        panel.dialog("close");
                                        panel.dialog("destroy");
                                        panel.remove();
                                    }
                                }, "JSON");
                            }
                        },
                        {
                            text: "关闭",
                            handler: function () {
                                panel.dialog("close");
                                panel.dialog("destroy");
                                panel.remove()
                            }
                        }
                    ]
                });
            });
        }

        function whenViewHistory(id) {
            if (!cache[id]) {
                $("body").wait("start", "实验历史加载中，请稍等！");
                $.ajax({
                    url: ctx + "/app/api/lab/labRecords",
                    data: {id: id},
                    success: function (data) {
                        $("body").wait("end");
                        for(var i in cache){
                            cache[i].store.selected = false;
                        }
                        cache[id] = {
                            store:{
                                text:data,
                                selected:true
                            }
                        };
                        render(data);
                    }
                })
            }else{
                if(cache[id].store.selected){
                    return;
                }
                for(var i in cache){
                    cache[i].store.selected = false;
                }
                cache[id].store.selected = true;
                render(cache[id].store.text);
            }
        }

        function render(txt) {
            page.getJqDom("history").html(txt);
            page.getJqDom("view").linkbutton({
                onClick: function () {
                    var id = $(this).attr("data-ref");
                    globalWindow.create({
                        width: 700,
                        href: ctx + "/app/api/lab/view?id=" + id,
                        title: "工艺详细参数"
                    });
                    globalWindow.open();
                }
            });
            page.getJqDom("edit").linkbutton({
                onClick: function () {
                    var id = $(this).attr("data-ref");
                    modifyProcess(id);
                }
            });
        }
    }
});